package com.huiyujiaoyu.powertime.ui.home;


import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.huiyujiaoyu.base.BaseFragment;
import com.huiyujiaoyu.http.HttpApi;
import com.huiyujiaoyu.http.HttpMethods;
import com.huiyujiaoyu.powertime.R;
import com.huiyujiaoyu.powertime.model.IndexItemModel;
import com.huiyujiaoyu.powertime.model.IndexListBean;
import com.huiyujiaoyu.powertime.model.SimpleListBean;
import com.huiyujiaoyu.util.ActivityUtil;
import com.huiyujiaoyu.util.Constant;
import com.huiyujiaoyu.util.DisplayUtil;
import com.huiyujiaoyu.util.GlideUtil;
import com.huiyujiaoyu.util.StringUtils;
import com.huiyujiaoyu.util.ViewFindUtils;
import com.huiyujiaoyu.widget.GridSpacingItemDecoration;
import com.huiyujiaoyu.widget.LlkjToolBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.R.attr.type;


/**
 * 首页
 * Created by yujunlong on 2016/12/5.
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener {
    @BindView(R.id.toolbar)
    LlkjToolBar mToolbar;
    @BindView(R.id.rv_content)
    RecyclerView mRvContent;
    @BindView(R.id.ll_serarch)
    LinearLayout mLlSerarch;
    @BindView(R.id.ibtn_xiaoxi)
    ImageButton mIbtnXiaoxi;
    @BindView(R.id.fl_msg)
    FrameLayout mFlMsg;
    @BindView(R.id.rl_score)
    RelativeLayout mRlScore;
    private BaseQuickAdapter<IndexListBean,BaseViewHolder> adapter;
    private List<IndexListBean> datas;
    private View header;
    ConvenientBanner convenientBanner;

    private TextView tv_progress,tv_task,tv_item_more,tv_hot_title;
    private ImageView iv_hot,iv_order;
    private ProgressBar pb_progressbar;
    int imageHeight;
    public static HomeFragment newInstance() {
        Bundle args = new Bundle();
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void userBundle(Bundle savedInstanceState) {
        super.userBundle(savedInstanceState);
    }

    @Override
    protected void initView() {
        super.initView();
        setToolbar(mToolbar);
        mToolbar.setToolBar("首页", true, "", R.mipmap.icon_home_search_s, true, "", R.mipmap.icon_home_message_s);
        header = LayoutInflater.from(mContext).inflate(R.layout.header_home,null);
        convenientBanner = ViewFindUtils.find(header,R.id.convenientBanner);
        tv_progress = ViewFindUtils.find(header,R.id.tv_progress);
        tv_task = ViewFindUtils.find(header,R.id.tv_task);
        tv_item_more = ViewFindUtils.find(header,R.id.tv_item_more);
        tv_hot_title = ViewFindUtils.find(header,R.id.tv_hot_title);
        iv_hot = ViewFindUtils.find(header,R.id.iv_hot);
        iv_order = ViewFindUtils.find(header,R.id.iv_order);
        pb_progressbar = ViewFindUtils.find(header,R.id.pb_progressbar);
        HttpMethods.getInstance().index(mContext,getComp(),this);

    }

    @Override
    protected void initData() {
        super.initData();
        initAdapter();
    }

    @Override
    protected void initListener() {
        super.initListener();
        mRvContent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if(getDistanceToTop()<=imageHeight){
                    mToolbar.setVisibility(View.GONE);
                    mRlScore.setVisibility(View.VISIBLE);
                }else{
                    mToolbar.setVisibility(View.VISIBLE);
                    mRlScore.setVisibility(View.GONE);
                }

            }
        });
        mToolbar.setLeftButtonOnClickLinster(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        mToolbar.setRightButtonOnClickLinster(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        tv_item_more.setOnClickListener(this);
        iv_hot.setOnClickListener(this);
    }

    private void initAdapter(){
        datas = new ArrayList<>();
        adapter = new BaseQuickAdapter<IndexListBean, BaseViewHolder>(R.layout.item_home,datas) {
            @Override
            protected void convert(BaseViewHolder helper, final IndexListBean item) {
                final RecyclerView rv_item_one = helper.getView(R.id.rv_item_content);
                helper.setText(R.id.tv_item_title,item.name);
                helper.getView(R.id.tv_item_more).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        HotListActivity.launch(mContext,item.type+1);
                    }
                });
                switch (item.type) {
                    case 0:
                        rv_item_one.setLayoutManager(new GridLayoutManager(mContext, 2));
                        rv_item_one.addItemDecoration(new GridSpacingItemDecoration(2,DisplayUtil.dip2px(mContext,10),true,false));
                        break;
                    case 1:
                        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
                        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                        rv_item_one.setLayoutManager(linearLayoutManager);
                        break;
                    case 2:
                        rv_item_one.setLayoutManager(new LinearLayoutManager(mContext));
                        break;
                }
                rv_item_one.setAdapter(getAdapter(item.datas,item.type));
                setRvContent(rv_item_one,item.datas,item.type);
            }
        };
        mRvContent.setHasFixedSize(true);
        mRvContent.setLayoutManager(new LinearLayoutManager(mContext));
        adapter.addHeaderView(header);
        mRvContent.setAdapter(adapter);
    }

    private void setRvContent(RecyclerView rv_item_one, final List<IndexItemModel> datas, final int type){
        rv_item_one.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (type) {
                    case 0://视频
                        Bundle b = new Bundle();
                        b.putString(Constant.DATA,datas.get(position).content_id+"");
                        ActivityUtil.startActivity(mContext,ShiPinDetailActivity.class,b);
                        break;
                    case 1://语音
                         b = new Bundle();
                        b.putString(Constant.DATA,datas.get(position).content_id+"");
                        ActivityUtil.startActivity(mContext,VoiceDetailActivity.class,b);
                        break;
                    case 2://文本
                        ArticleDetailsActivity.launch(mContext,datas.get(position).content_id+"");
                        break;
                }
            }
        });
    }

    public BaseQuickAdapter<IndexItemModel, BaseViewHolder> getAdapter(List<IndexItemModel> datas, final int type){
        int resd = -1;
        switch (type) {
            case 0:
            case 1:
                resd =  R.layout.item_homeone4;
                break;
            case 2:
                resd =  R.layout.cell_hot_article;
                break;
        }
        BaseQuickAdapter<IndexItemModel, BaseViewHolder> adapter = new BaseQuickAdapter<IndexItemModel, BaseViewHolder>(resd, datas) {
            @Override
            protected void convert(BaseViewHolder helper, IndexItemModel item) {
                switch (type) {
                    case 0:
                        TextView tv_zj = helper.getView(R.id.tv_zhagnjie);
                        ImageView iv_item_play = helper.getView(R.id.iv_item_play);
                        iv_item_play.setVisibility(View.VISIBLE);
                        tv_zj.setVisibility(View.VISIBLE);
                        helper.setText(R.id.tv_item_title, item.title)
                                .setText(R.id.tv_item_name, item.name);
                        tv_zj.setText("共" + item.chapter_count + "章");
                        GlideUtil.loadImg((ImageView) helper.getView(R.id.iv_bg),StringUtils.getFullUrl(item.cover));
                        break;
                    case 1:
                        int width = DisplayUtil.getWidth(mContext,10,2,10)+DisplayUtil.dip2px(mContext,10);
                         RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) helper.getView(R.id.ll_headline).getLayoutParams();
                         params.width = width;
                         params.setMarginStart(DisplayUtil.dip2px(mContext,10));
                         tv_zj = helper.getView(R.id.tv_zhagnjie);
                         iv_item_play = helper.getView(R.id.iv_item_play);
                        iv_item_play.setVisibility(View.GONE);
                        tv_zj.setVisibility(View.GONE);
                        helper.setText(R.id.tv_item_title, item.title)
                                .setText(R.id.tv_item_name, item.name);
                        GlideUtil.loadImg((ImageView) helper.getView(R.id.iv_bg),StringUtils.getFullUrl(item.cover));
                        break;
                    case 2:
                        helper.setText(R.id.tv_title, item.title)
                                .setText(R.id.tv_author, item.name)
                                .setText(R.id.tv_read_count, String.valueOf(item.view_count))
                                .setText(R.id.tv_comment_count, String.valueOf(item.comment_count));
                        GlideUtil.loadImg((ImageView) helper.getView(R.id.iv_pic),StringUtils.getFullUrl(item.cover));
                        break;
                }
            }
        };
        return adapter;
    }

    private String hot_content_id;
    @Override
    public void onNext(Object o, int httpcode) {
        super.onNext(o, httpcode);
        switch (httpcode) {
            case HttpApi.HTTP_INDEX:
                SimpleListBean bean = (SimpleListBean) o;
                datas.add(new IndexListBean(bean.videoList,0,"热门视频"));
                datas.add(new IndexListBean(bean.audioList,1,"热门聆听"));
                datas.add(new IndexListBean(bean.articleList,2,"热门文章"));
                setBanner(bean.carousels);
                imageHeight = convenientBanner.getHeight();
                pb_progressbar.setProgress(Integer.parseInt(bean.completed));
                tv_progress.setText(bean.completed + "%");
                GlideUtil.loadImg(iv_hot,StringUtils.getFullUrl(bean.article.cover));
                hot_content_id = bean.article.content_id+"";
                GlideUtil.loadImg(iv_order,StringUtils.getFullUrl(bean.subscribe.cover));
                tv_hot_title.setText(bean.article.title);
                adapter.notifyDataSetChanged();
                break;
        }
    }
    //设置轮播图
    public void setBanner(List<IndexItemModel> carousels) {
        convenientBanner.setPages(
                new CBViewHolderCreator<LocalImageHolderView>() {
                    @Override
                    public LocalImageHolderView createHolder() {
                        return new LocalImageHolderView();
                    }
                }, carousels)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.mipmap.banner_lunbo_n, R.mipmap.banner_lunbo_s})
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);  //设置指示器的方向
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_item_more:
                ActivityUtil.startActivity(mContext, HotTopActivity.class);
                break;
            case R.id.iv_hot:
                HeadingDetailsActivity.launch(mContext,hot_content_id);
                break;
        }
    }

    public class LocalImageHolderView implements Holder<IndexItemModel> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);

            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, IndexItemModel data) {
            GlideUtil.loadImg(imageView, StringUtils.getFullUrl(data.cover));
        }

    }

    List<Integer> headerHeightArray;
    private int getDistanceToTop(){
        LinearLayoutManager layoutManager = (LinearLayoutManager) mRvContent.getLayoutManager();
        // 获取第一个可见item的位置
        int position = layoutManager.findFirstVisibleItemPosition();
        // 获取第一个可见item
        View firstVisiableChildView = layoutManager.findViewByPosition(position);

        // 必须考虑有没有Header  预存下所有header的高度
        int headerCount = adapter.getHeaderLayoutCount();
        if (headerCount > 0) {
            if (headerHeightArray == null) {
                headerHeightArray = new ArrayList<>();
            }
            if (position < headerCount) {
                View headerView_i = layoutManager.findViewByPosition(position);
                headerHeightArray.add(headerView_i.getHeight());
            }
        }

        // 获取第一个可见item的高度
        int itemHeight = firstVisiableChildView.getHeight();
        // 获取第一个可见item的位置
        int distance = 0;
        if (position == 0) {
            distance = (position) * itemHeight - firstVisiableChildView.getTop();
        } else {
            int allHeaderHeight = 0;
            for (int i = 0; i < position; i++) {
                allHeaderHeight = allHeaderHeight + headerHeightArray.get(i);
            }
            distance = (position) * itemHeight - firstVisiableChildView.getTop() + allHeaderHeight;
        }
        return distance;
    }
}
